/*
-----------------------------------------------------------------------------
This source file is part of as4game
    (ActionScript For Game Engine)
For the latest info, see http://as4game.googlecode.com

Copyright (c) 2000-2011 Hproof Software Ltd

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
package
{
	import com.adobe.utils.AGALMiniAssembler;
	
	import flash.display.Sprite;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;
	import flash.display3D.Context3D;
	import flash.display3D.Context3DProgramType;
	import flash.display3D.Context3DTriangleFace;
	import flash.display3D.Context3DVertexBufferFormat;
	import flash.display3D.IndexBuffer3D;
	import flash.display3D.Program3D;
	import flash.display3D.VertexBuffer3D;
	import flash.display3D.textures.Texture;
	import flash.events.Event;
	import flash.geom.Matrix3D;
	import flash.geom.Rectangle;
	import flash.geom.Vector3D;
	import flash.text.TextField;
	import flash.utils.getTimer;
	
	import org.as4game.common.math.Vector3;
	import org.as4game.common.utils.Fps;
	import org.as4game.common.utils.KeyboardState;
	import org.as4game.render3d.Render3D;
	import org.as4game.resource.bitmap.Material;
	import org.as4game.scene3d.Camera;
	import org.as4game.scene3d.Node;
	import org.as4game.scene3d.Plane;
	import org.as4game.scene3d.Scene;
	import org.as4game.scene3d.SceneNode;
	
	/**
	 * TestRender
	 */
	public class TestRender extends Sprite
	{
		public function TestRender()
		{
			stage.scaleMode = StageScaleMode.NO_SCALE;
			stage.align = StageAlign.TOP_LEFT;
			
			test_render3d();
		}
		
		//	
		private var info:TextField;
		private var fps:Fps;
		private var keyState:KeyboardState;
		
		private var scene:Scene;
		private var camera:Camera;
		private var planeNode:SceneNode;
		private var plane:Plane;
		
		[Embed( source = "../res/window.jpg" )]
		protected const txt_sword_class:Class;
		private var material:Material;
		
		private const WIDTH:int = 900; 
		private const HEIGHT:int = 500;
		private var render3d:Render3D;
		private var context3d:Context3D;
		
		// 
		private function test_render3d():void{
			
			//
			info = new TextField;
			info.autoSize = "left";
			info.mouseEnabled = false;
			info.background = true;
			info.backgroundColor = 0;
			addChild(info);
			
			fps = new Fps();
			
			keyState = new KeyboardState( stage );
			
			// scene
			scene = new Scene();
			
			camera = new Camera("main camera");
			scene.root.addChild( new SceneNode( null, camera ) );
			camera.sceneNode.mLocalMatrix.appendTranslation( 0, 0, 10 );
			camera.sceneNode.setLocalChanged();
			camera.aspect = WIDTH / HEIGHT;
			
			planeNode = new SceneNode("planeNode");
			scene.root.addChild( planeNode );
			
			material = Material.fromBitmap( (new txt_sword_class).bitmapData );
			
			plane = new Plane;
			plane.createPlane();
			plane.material = material;
			planeNode.attachObject( plane );
			
			for(var i:int=0; i<= 50; i++){
				var p:Plane = new Plane;
				p.createPlane();
				p.material = material;
				scene.root.addChild( new SceneNode(null, p ) );
				p.sceneNode.mLocalMatrix.appendTranslation( 0, 0, -5 * i );
				p.sceneNode.setLocalChanged();
			}
			
			// render
			render3d = new Render3D( stage, onCreate );
			function onCreate(render3d:Render3D):void{
				context3d = render3d.context3D;
				doInit();
			}
		}
		
		private var program:Program3D;
		private var indexBuf:IndexBuffer3D;
		private var vertexBuf:VertexBuffer3D;
		private function doInit():void{
			
			// program
			var vasm: AGALMiniAssembler = new AGALMiniAssembler();
			vasm.assemble( Context3DProgramType.VERTEX,
				"m44 op, va0, vc12	\n" +	// 4x4 matrix transform from stream 0 to output clipspace
//				"dp4 vt0.x, va0, vc12\n"+		// 骨骼矩阵开始于 [14], 这里取骨骼矩阵, 并变化坐标
//				"dp4 vt0.y, va0, vc13\n"+    	
//				"dp4 vt0.z, va0, vc14\n"+	
//				"dp4 vt0.w, va0, vc15\n"+						
//				"mov op, vt0\n"+		
//				"mov op, va0			\n" +	// 不做任何变化, 使用原始坐标
				"mov v0, va1			\n"  	// copy stream 1 to fragment 
			);						
			var fasm: AGALMiniAssembler= new AGALMiniAssembler(); 
			fasm.assemble( Context3DProgramType.FRAGMENT,
//				"mov oc, v0" // output color  
				"mov ft0, v0\n"+
				"tex ft1, ft0, fs0 <2d,clamp,linear>\n"+ // sample texture 0			
				"mov oc, ft1\n"
			);
			
			program = context3d.createProgram();
			program.upload( vasm.agalcode, fasm.agalcode );
			
			// buffer
			indexBuf = context3d.createIndexBuffer( 6 );
			indexBuf.uploadFromVector( Vector.<uint>( [0, 1, 2, 1, 3, 2] ), 0, 6 );	// 左手坐标
			
			const z:Number = 0;
			vertexBuf = context3d.createVertexBuffer( 4, 5 );
			vertexBuf.uploadFromVector( Vector.<Number>([
				-1, -1, z, 0, 0,		// X=向右, Y=向下, Z=向屏幕外, 纹理左上角为0,0. 绘制的时候, 需要倒置Y
				1, -1, z, 1, 0,
				-1, 1, z, 0, 1,
				1, 1, z, 1, 1,
				]), 0, 4);
			
			// start render
			render3d.viewport = new Rectangle(0, 0, WIDTH, HEIGHT );
			context3d.configureBackBuffer( WIDTH, HEIGHT, 1);
			
			stage.addEventListener( Event.ENTER_FRAME, onEnterFrame);
		}
		
		private function onEnterFrame(e:Event):void{
			
			// 更新信息显示
			fps.update();
			info.htmlText = "<font color='#00ff00'>FPS: " + fps.fps + "</font>";
			
			// 移动摄像机, 根据键盘输入
			var move:Matrix3D = keyState.getMoveMatrix( 0.1, 1);
			camera.node.mLocalMatrix.prepend( move );		// 先进行 move 变化, 然后加上原来的变化. 结果就是 move 作为本地变化
			camera.node.setLocalChanged();
			
			render1();
//			render2();
//			render3();
		}
		
		private function render1():void{
			
			// 得到 view, projection, model, mvp
			scene.updateWorldMatrix();
			
			var model:Matrix3D = planeNode.mWorldMatrix.clone();		// 模型坐标系 -> 世界坐标系
			
			var view:Matrix3D = camera.node.mWorldMatrix.clone();	// 像机坐标系 -> 世界坐标系
			view.invert();											// 世界坐标系 -> 相机坐标系
			
			var projection:Matrix3D = camera.projection.clone();	// 空间坐标系 -> 透视坐标系 
//			var projection:Matrix3D = Camera.makeRectangularProjection(-10, 10, -10, 10, -100, 0); 
			
			var mvp:Matrix3D = model.clone();		// 模型 -> 世界
			mvp.append( view );						// 世界 -> 像机
			mvp.append( projection );				// 相机 -> 透视   => 模型 -> 透视
			
			// 渲染对象
			context3d.clear();
			context3d.setCulling( Context3DTriangleFace.NONE );
			
//			context3d.setProgramConstantsFromMatrix( Context3DProgramType.VERTEX, 0, model, true);		// [0] = model
//			context3d.setProgramConstantsFromMatrix( Context3DProgramType.VERTEX, 4, view, true);		// [4] = view-inv
//			context3d.setProgramConstantsFromMatrix( Context3DProgramType.VERTEX, 8, projection, true);	// [8] = project
			context3d.setProgramConstantsFromMatrix( Context3DProgramType.VERTEX, 12, mvp, true);		// [12] = mvp
			
			context3d.setProgram( program );
			context3d.setVertexBufferAt( 0, vertexBuf, 0, Context3DVertexBufferFormat.FLOAT_3 );
			context3d.setVertexBufferAt( 1, vertexBuf, 3, Context3DVertexBufferFormat.FLOAT_2 );
			context3d.setTextureAt(0, material.getTexture( context3d ) );
			context3d.drawTriangles( indexBuf, 0, 1 );
			
			context3d.present();
		}
		
		private function render2():void{
			
			//
			context3d.clear();
			context3d.setCulling( Context3DTriangleFace.NONE );
			
			context3d.setProgram( program );
			context3d.setVertexBufferAt( 0, vertexBuf, 0, Context3DVertexBufferFormat.FLOAT_3 );
			context3d.setVertexBufferAt( 1, vertexBuf, 3, Context3DVertexBufferFormat.FLOAT_2 );
			context3d.setTextureAt(0, material.getTexture( context3d ) );
			
			// 建立 hcount*vcount 个模型矩阵
			const hcount:int = 9;
			const vcount:int = 5;
			
			var vp:Matrix3D = Camera.makeRectangularProjection( -hcount, hcount, -vcount, vcount, -100, 100);
			var x0:Number = - hcount + 1;
			var y0:Number = - vcount + 1;
			for(var y:int=0; y<vcount; y++){
				for(var x:int=0; x<hcount; x++){
					var m:Matrix3D = new Matrix3D;
					m.appendRotation( - (getTimer() / 10 ) % 360, Vector3D.Y_AXIS );
					m.appendRotation( -45, Vector3D.X_AXIS );
					m.appendTranslation( x0 + x * 2, y0 + y * 2, 0 );
					m.append( vp );
					
					context3d.setProgramConstantsFromMatrix( Context3DProgramType.VERTEX, 12, m, true);		// [12] = mvp
					context3d.drawTriangles( indexBuf, 0, 2 );
				}
			}
			
			//
			context3d.present();
		}
		
		private function render3():void{
			render3d.render( scene, camera  );
		}
	}
}
